package com.joolun.web.ipaynow;

import com.joolun.system.domain.PayParam;
import com.joolun.web.ipaynow.utils.MD5Facade;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PayUtil {
    /**
     * 格式化日期
     * @return
     */
    public static String formatDateToStr(Date date) {
        if (date == null) return null;

        Instant instant = date.toInstant();
        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        return localDateTime.format(formatter);
    }

    /**
     * 做MD5签名
     * @return
     */
    public static Map<String, String> getMhtSignature(PayParam payParam){
        // 做MD5签名
        Map<String, String> dataMap = new HashMap<>();
        if(!isFieldEmpty(payParam,"funcode")){
            dataMap.put("funcode", payParam.getFuncode());
        }
        if(!isFieldEmpty(payParam,"version")){
            dataMap.put("version", payParam.getVersion());
        }
        if(!isFieldEmpty(payParam,"appId")){
            dataMap.put("appId", payParam.getAppId());
        }
        if(!isFieldEmpty(payParam,"mhtOrderNo")){
            dataMap.put("mhtOrderNo", payParam.getMhtOrderNo());
        }
        // 商户在现在支付开通的子商户号 开通服务商模式的商户必传
//        if(!isFieldEmpty(payParam,"mhtSubMchId")){
//            dataMap.put("mhtSubMchId", payParam.getMhtSubMchid());
//        }
        if(!isFieldEmpty(payParam,"mhtOrderName")){
            dataMap.put("mhtOrderName", payParam.getMhtOrderName());
        }
        if(!isFieldEmpty(payParam,"mhtOrderType")){
            dataMap.put("mhtOrderType", payParam.getMhtOrderType());
        }
        if(!isFieldEmpty(payParam,"mhtCurrencyType")){
            dataMap.put("mhtCurrencyType", payParam.getMhtCurrencyType());
        }
        if(!isFieldEmpty(payParam,"mhtOrderAmt")){
            dataMap.put("mhtOrderAmt", payParam.getMhtOrderAmt().toString());
        }
        if(!isFieldEmpty(payParam,"mhtOrderDetail")){
            dataMap.put("mhtOrderDetail", payParam.getMhtOrderDetail());
        }
        // 默认 3600
//        if(!isFieldEmpty(payParam,"mhtOrderTimeOut")){
//            dataMap.put("mhtOrderTimeOut", payParam.getMhtOrderTimeOut().toString());
//        }
        if(!isFieldEmpty(payParam,"mhtOrderStartTime")){
            dataMap.put("mhtOrderStartTime", payParam.getMhtOrderStartTime());
        }
        if(!isFieldEmpty(payParam,"notifyUrl")){
            dataMap.put("notifyUrl", payParam.getNotifyUrl());
        }
        if(!isFieldEmpty(payParam,"frontNotifyUrl")){
            dataMap.put("frontNotifyUrl", payParam.getFrontNotifyUrl());
        }
        if(!isFieldEmpty(payParam,"mhtCharset")){
            dataMap.put("mhtCharset", payParam.getMhtCharset());
        }
        if(!isFieldEmpty(payParam,"deviceType")){
            dataMap.put("deviceType", payParam.getDeviceType());
        }
        if(!isFieldEmpty(payParam,"payChannelType")){
            dataMap.put("payChannelType", payParam.getPayChannelType());
        }
        if(!isFieldEmpty(payParam,"outputType")){
            dataMap.put("outputType", payParam.getOutputType());
        }
        // outputType=1 必填，值为用户关注公众号后的 openid，注：当渠道类型为 11 时，不填写
//        if(!isFieldEmpty(payParam,"consumerId")){
//            dataMap.put("consumerId", payParam.getConsumerId());
//        }
        if(!isFieldEmpty(payParam,"mhtLimitPay")){
            dataMap.put("mhtLimitPay", payParam.getMhtLimitPay());
        }
        if(!isFieldEmpty(payParam,"mhtSignType")){
            dataMap.put("mhtSignType", payParam.getMhtSignType());
        }
        //商户保留域， 可以不用填。 如果商户有需要对每笔交易记录一些自己的东西，可以放在这个里面
//        if(!isFieldEmpty(payParam,"mhtReserved")){
//            dataMap.put("mhtReserved", payParam.getMhtReserved());
//        }

        // 密钥是用户在注册应用的时候生成的，每个应用一个 MD5 密钥
        String appKey = "gh4HwH7UarOCXRtP96lPD9KQd8xiEpT9";
        String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8");
        dataMap.put("mhtSignature", mhtSignature);
        return dataMap;
    }

    /**
     * 判断对象的某个属性是否为空（支持多种类型）
     * @param obj       待检查的对象
     * @param fieldName 属性名
     * @return true-属性为空；false-属性不为空
     */
    public static boolean isFieldEmpty(Object obj, String fieldName) {
        if (obj == null || fieldName == null || fieldName.isEmpty()) {
            return true;
        }

        try {
            // 获取对象的属性
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true); // 允许访问私有属性

            // 获取属性值
            Object value = field.get(obj);

            // 判断值是否为空
            if (value == null) {
                return true;
            }

            // 根据不同类型判断
            if (value instanceof String) {
                return ((String) value).trim().isEmpty();
            } else if (value instanceof Number) {
                // 处理所有数值类型（包括 Long、Integer、Double 等）
                if (value instanceof BigDecimal) {
                    return ((BigDecimal) value).compareTo(BigDecimal.ZERO) == 0;
                } else {
                    return ((Number) value).doubleValue() == 0;
                }
            } else if (value instanceof Boolean) {
                // 可选：根据业务需求判断布尔值是否为空
                return !(Boolean) value;
            }

            // 其他类型默认不为空（可根据需要扩展）
            return false;

        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 处理反射异常（如属性不存在）
            System.err.println("检查属性失败: " + e.getMessage());
            return true; // 发生异常时默认属性为空
        }
    }

}
